import { create } from "zustand";
import { fetchDashboardOverview } from "@/api/Home/home";
import type { RootResponse, JobPersonnel } from "@/api/Home/type";

import fault from "@/assets/icon/fault.png";
import cutover from "@/assets/icon/cutover.png";
import daydate from "@/assets/icon/daydate.png";
import workorder from "@/assets/icon/workorder.png";
import important from "@/assets/icon/important.png";

interface DashboardItem {
    name: string;
    value: number;
    url: string | null;
}

interface GroupedDataItem {
    groupName: string;
    icon: string;
    items: DashboardItem[];
}

interface DashboardState {
    groupedData: GroupedDataItem[];
    jobPersonnel: JobPersonnel;
    workSchedule: string;
    scheduleRecord: string;
    employeeRunCount: DashboardItem;
    onlineEmployee: DashboardItem;
    networkSituaiton: string;
    eventOverview: string;
    cut_checkurl: string;
    weekreporturl: string;
    fetchData: () => Promise<void>;
}


const defaultJobPersonnel: JobPersonnel = {
    value: {
        dutyOfficer: [],
        majorCorePosition: [],
        majorAccessPosition: [],
    },
    url: "",
};

const defaultEmployeeRunCount: DashboardItem = {
    name: "数字员工累计运行次数",
    value: 0,
    url: "",
};

const defaultOnlineEmployee: DashboardItem = {
    name: "当前在线数字员工",
    value: 0,
    url: "",
};


const Mapping: { [key: string]: string } = {
    todayEvent: "今日故障事件",
    incompleteEvent: "未完成故障事件",
    pendingManualActionEvent: "需人工介入事件",

    incompleteOrder: "未完成工单",
    timeOutOrder: "超时工单",
    dispatchFaultOrder: "派发的故障工单",

    todayCut: "当日完成ABCD类割接",
    incompleteCut: "明日计划ABCD类割接",

    incompleteComplaintOrder: "未完成工单",
    timeOutComplaintOrder: "超时工单",
    dispatchComplaintOrder: "派发投诉工单",

    dailyRoutine: "日常事务超时情况",

    importantEvent: "重大活动彩信发布",
    holidayEvent: "节假日彩信发布",
    publicOpinion: "舆情数量",
};

const groupsDefinition = [
    {
        groupName: "故障事件",
        icon: fault,
        keys: [
            "todayEvent",
            "incompleteEvent",
            "pendingManualActionEvent",
            "incompleteOrder",
            "timeOutOrder",
            "dispatchFaultOrder",
        ],
    },
    {
        groupName: "交割管理",
        icon: cutover,
        keys: ["todayCut", "incompleteCut"],
    },
    {
        groupName: "日常工作",
        icon: daydate,
        keys: ["dailyRoutine"],
    },
    {
        groupName: "投诉工单",
        icon: workorder,
        keys: [
            "incompleteComplaintOrder",
            "timeOutComplaintOrder",
            "dispatchComplaintOrder",
        ],
    },
    {
        groupName: "重要保障",
        icon: important,
        keys: ["importantEvent", "holidayEvent", "publicOpinion"],
    },
];

export const useDashboardStore = create<DashboardState>((set) => ({
    groupedData: groupsDefinition.map((group) => ({
        groupName: group.groupName,
        icon: group.icon,
        items: group.keys.map((key) => ({
            name: Mapping[key] || key,
            value: 10,
            url: "",
        })),
    })),
    jobPersonnel: defaultJobPersonnel,
    workSchedule: "",       // 初始为空字符串
    scheduleRecord: "",
    employeeRunCount: defaultEmployeeRunCount,
    onlineEmployee: defaultOnlineEmployee,
    networkSituaiton: "", //网络态势感知链接
    eventOverview: '',
    cut_checkurl: '',
    weekreporturl: '',


    fetchData: async () => {
        try {
            const res: RootResponse = await fetchDashboardOverview();
            const raw = res.data;

            const updatedData = groupsDefinition.map((group) => ({
                groupName: group.groupName,
                icon: group.icon,
                items: group.keys.map((key) => {
                    const item = (raw as any)[key];
                    return {
                        name: Mapping[key] || key,
                        value: Number(item?.value ?? 0),
                        url: item?.url ?? "",
                    };
                }),
            }));

            const runCountData = raw.employeeRunCount ?? {};
            const onlineEmployeeData = raw.onlineEmployee ?? {};




            raw.jobPersonnel.value = JSON.parse(raw.jobPersonnel.value)


            set({
                groupedData: updatedData,
                jobPersonnel: raw.jobPersonnel ?? defaultJobPersonnel,
                workSchedule: raw.workSchedule?.url ?? "",
                scheduleRecord: raw.scheduleRecord?.url ?? "",
                networkSituaiton: raw.networkSituaiton?.url ?? "",
                eventOverview: raw.eventOverview?.url ?? "",
                cut_checkurl: raw.cut_check?.url ?? "",
                weekreporturl: raw.weekreport?.url ?? "",

                employeeRunCount: {
                    name: "数字员工累计运行次数",
                    value: Number(runCountData.value ?? 0),
                    url: runCountData.url ?? ""
                },
                onlineEmployee: {
                    name: "当前在线数字员工",
                    value: Number(onlineEmployeeData.value ?? 0),
                    url: onlineEmployeeData.url ?? ""
                },
            });
        } catch (error) {
            console.error("Dashboard fetch error:", error);
            set({
                jobPersonnel: defaultJobPersonnel,
                workSchedule: "",
                scheduleRecord: "",
            });
        }
    },
}));



